#include "../server.hpp"
#include <vector>
#include <fstream>
#include <sys/stat.h>
#include <regex>
#define DEFALT_TIMEOUT 10
#define Max_Line 8192
std::unordered_map<int, std::string> _statu_msg = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> _mime_msg = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

class Util
{
public:
    // 切割字符串
    static uint64_t Split(const std::string &src, const std::string &sep, std::vector<std::string> *arry)
    {
        int offset = 0;
        while (offset < src.size())
        {
            std::string res;
            // abc,,,b,,,c,
            size_t pos = src.find(sep, offset); // 在src字符串偏移量offset处，开始向后查找sep字符/字串，返回查找到的位置
            if (pos == std::string::npos)
            {
                if (pos == offset)
                    break;
                arry->push_back(src.substr(offset));
                return arry->size();
            }
            if (pos == offset)
            {
                offset = pos + sep.size();
                continue;
            }
            arry->push_back(src.substr(offset, pos - offset));
            offset = pos + sep.size();
        }
        return arry->size();
    }
    // 读取文件所有内容
    static bool ReadFile(const std::string &filename, std::string *buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (!ifs.is_open())
        {
            ERR_LOG("Open file error");
            ifs.close();
            return false;
        }
        size_t fsize = 0;
        ifs.seekg(0, ifs.end); // 读取跳转到末尾
        fsize = ifs.tellg();   // 获取当前读写位置相对于起始位置的偏移量，从末尾偏移刚好就是文件大小
        buf->resize(fsize);    // buf扩容存储
        ifs.seekg(0, ifs.beg);
        ifs.read(&(*buf)[0], fsize);
        if (ifs.good() == false)
        {
            ERR_LOG("Read error");
            ifs.close();
            return false;
        }
        ifs.close();
        return true;
    }
    // 文件写
    static bool WtiteFile(const std::string &filename, const std::string &buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (!ofs.is_open())
        {
            ERR_LOG("Open file error");
            ofs.close();
            return false;
        }
        ofs.write(buf.c_str(), buf.size());
        if (ofs.good() == false)
        {
            ERR_LOG("WRITE %s FILE FAILED!", filename.c_str());
            ofs.close();
            return false;
        }
        ofs.close();
        return true;
    }
    // URL编码，避免URL中资源路径与查询字符串中的特殊字符与HTTP请求中特殊字符产生歧义
    // 编码格式：将特殊字符的ascii值，转换为两个16进制字符，前缀%   C++ -> C%2B%2B
    //   不编码的特殊字符： RFC3986文档规定 . - _ ~ 字母，数字属于绝对不编码字符
    // RFC3986文档规定，编码格式 %HH
    // W3C标准中规定，查询字符串中的空格，需要编码为+， 解码则是+转空格
    //  url编码
    static std::string Encode(const std::string url, bool is_encode_space)
    {
        std::string res;
        for (auto c : url)
        {
            if (c == '.' || c == '-' || c == '~' || c == '_' || isalnum(c))
            {
                res += c;
                continue;
            }
            if (c == ' ' && is_encode_space)
            {
                res += '+';
                continue;
            }
            char tmp[4] = {0};
            // snprintf 与 printf比较类似，都是格式化字符串，只不过一个是打印，一个是放到一块空间中
            snprintf(tmp, 4, "%%%02X", c);
            res += tmp;
        }
        return res;
    }
    static char HxToint(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        else if (c >= 'a' && c <= 'z')
            return c - 'a' + 10;
        else if (c >= 'A' && c <= 'Z')
            return c - 'A' + 10;
        return -1;
    }
    // url解码
    static std::string Decode(const std::string &url, bool is_decode_space)
    {
        std::string res;
        for (int i = 0; i < url.size();)
        {
            if (url[i] == '+' && is_decode_space)
            {
                res += ' ';
                i++;
            }
            else if (url[i] == '%' && (i + 2) < url.size())
            {
                char v1 = HxToint(url[i + 1]);
                char v2 = HxToint(url[i + 2]);
                char v = v1 * 16 + v2;
                res += v;
                i += 3;
                continue;
            }
            else
            {
                res += url[i++];
            }
        }
        return res;
    }
    // 获取状态信息
    static std::string GetStatu(int statu_code)
    {
        auto it = _statu_msg.find(statu_code);
        if (it == _statu_msg.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 根据文件后缀名获得mime,..html\.png
    static std::string Getmime(const std::string &filename)
    {
        size_t pos = filename.find_last_of(".");
        if (pos == std::string::npos)
        {
            return "application/octet-stream";
        }
        std::string res = filename.substr(pos);
        auto it = _mime_msg.find(res);
        if (it == _mime_msg.end())
        {
            return "application/octet-stream";
        }
        return it->second;
    }
    // 判断是否是普通文件
    static bool Is_regularfile(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            DBG_LOG(" stat error ");
            return false;
        }
        return S_ISREG(st.st_mode);
    }
    // 目录
    static bool IsDirectory(const std::string &filename)
    {
        struct stat st;
        int ret = stat(filename.c_str(), &st);
        if (ret < 0)
        {
            return false;
        }
        return S_ISDIR(st.st_mode);
    }

    // http请求的资源路径有效性判断
    //  /index.html  --- 前边的/叫做相对根目录  映射的是某个服务器上的子目录
    //  想表达的意思就是，客户端只能请求相对根目录中的资源，其他地方的资源都不予理会
    //  /../login, 这个路径中的..会让路径的查找跑到相对根目录之外，这是不合理的，不安全的
    static bool ValidPath(const std::string &path)
    {
        std::string sep = "/";
        std::vector<std::string> res;
        Split(path, sep, &res);
        int level = 0;
        for (auto &c : res)
        {
            if (c == "..")
            {
                level--;
                if (level < 0)
                {
                    return false;
                }
                continue;
            }
            level++;
        }
        return true;
    }
};

class HttpRequest
{
public:
    std::string _method;  // 方法
    std::string _path;    // 路径
    std::string _version; // 协议版本
    std::smatch _matches; // 资源路径的正则提取数据
    // 正文
    std::string _body;
    // 头部字段
    std::unordered_map<std::string, std::string> _headers;
    // 查询字符串
    std::unordered_map<std::string, std::string> _params;

public:
    HttpRequest() : _version("HTTP/1.1") {}
    void ReSet()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        std::smatch match;
        _matches.swap(match);
        _headers.clear();
        _params.clear();
    }
    // 插入头部字段
    void SetHead(const std::string &key, const std::string &value)
    {
        _headers.insert(make_pair(key, value));
    }
    // 判断是否存在指定头部字段
    bool HasHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定头部字段的值
    std::string GetHeader(const std::string &key) const
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    // 插入查询字符串
    void SetParam(const std::string &key, const std::string &val)
    {
        _params.insert(std::make_pair(key, val));
    }
    // 判断是否有某个指定的查询字符串
    bool HasParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return false;
        }
        return true;
    }
    // 获取指定的查询字符串
    std::string GetParam(const std::string &key) const
    {
        auto it = _params.find(key);
        if (it == _params.end())
        {
            return "";
        }
        return it->second;
    }
    // 获取正文长度
    size_t GetContentLength()
    {
        bool ret = HasHeader("Content-Length");
        if (ret == false)
        {
            return 0;
        }
        std::string res = GetHeader("Content-Length");
        return std::stol(res);
    }
    // 判断长短连接
    bool Close()
    {
        // DBG_LOG("%d",HasHeader("Connection")==true);
        // DBG_LOG("%d",GetHeader("Connection")=="keep-alive");
        // DBG_LOG("[%s]",GetHeader("Connection").c_str());
        // 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
        if (HasHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }
     void ParsePostBody() 
     {
        // 只处理表单提交的默认格式
        if (GetHeader("Content-Type") != "application/x-www-form-urlencoded") {
            return;
        }
        std::vector<std::string> params;
        Util::Split(_body, "&", &params); // 按&分割键值对
        for (auto &p : params) {
            size_t pos = p.find("=");
            if (pos == std::string::npos) continue;
            std::string key = Util::Decode(p.substr(0, pos), true); // 解码（处理+转空格）
            std::string val = Util::Decode(p.substr(pos + 1), true);
            SetParam(key, val); // 存入_params，后续可用GetParam获取
        }
    }
};
// 响应
class HttpResponse
{
public:
    int _statu;
    bool _redirect_flag;
    std::string _body;
    std::unordered_map<std::string, std::string> _headers;
    std::string _redirect_url;

public:
    HttpResponse() : _statu(200) {}
    HttpResponse(int statu) : _statu(statu) {}
    void SetHeader(const std::string &key, const std::string &value)
    {
        _headers.insert(make_pair(key, value));
    }
    bool HashHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return false;
        }
        return true;
    }
    std::string GetHeader(const std::string &key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
        {
            return "";
        }
        return it->second;
    }
    void SetContent(const std::string &body, const std::string &type = "text/html")
    {
        _body = body;
        SetHeader("Content-Type", type);
    }
    void SetRedirect(std::string &url, int statu = 302) // 302临时重定向
    {
        _statu = statu;
        _redirect_flag = true;
        _redirect_url = url;
    }
    // 判断长短连接
    bool Close()
    {
        // 没有Connection字段，或者有Connection但是值是close，则都是短链接，否则就是长连接
        if (HashHeader("Connection") == true && GetHeader("Connection") == "keep-alive")
        {
            return false;
        }
        return true;
    }
};
typedef enum
{
    RECV_HTTP_ERROR,
    RECV_HTTP_LINE,
    RECV_HTTP_HEAD,
    RECV_HTTP_BODY,
    RECV_HTTP_OVER
} HttpRecvStatu;

class HttpContext
{
private:
    int _resp_statu;           // 响应状态码
    HttpRecvStatu _recv_statu; // 接受解析此时在那个状态
    HttpRequest _request;      // 得到此时请求信息
private:
    bool ParseLine(const std::string &line)
    {
        // std::string str = "GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1\r\n";
        std::smatch matches;
        std::regex e("(GET|HEAD|POST|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)?", std::regex::icase); // std::regex::icase忽略大小写匹配
        bool ret = std::regex_match(line, matches, e);
        if (ret == false)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400; // BAD REQUEST
            return false;
            ERR_LOG("匹配错误解析行");
        }
        // 0GET /bitejiuyeke/login?user=xiaoming&pass=123123 HTTP/1.1

        // 1GET
        // 2/bitejiuyeke/login
        // 3user=xiaoming&pass=123123
        // 4HTTP/1.1
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);
        _request._path = Util::Decode(matches[2], false);
        _request._version = matches[4];
        std::vector<std::string> s; // 存放key_value键值对
        std::string res = matches[3];
        std::string sep = "&";
        Util::Split(res, sep, &s);
        for (auto &ch : s)
        {
            size_t pos = ch.find("=");
            if (pos == std::string::npos)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 400; // BAD REQUEST
                return false;
            }
            std::string key = ch.substr(0, pos);
            std::string value = ch.substr(pos + 1);
            _request.SetParam(key, value);
        }
        return true;
    }
    bool RecvLine(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_LINE)
            return false;
        std::string line = buf->GetLineAndPop();
        if (line.size() == 0)
        {
            // 考虑缓冲区数据不到一行，但是一行内容过大也是错误
            if (buf->ReadAbleSize() > Max_Line)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // URI TOO LONG
                return false;
            }
            // 缓冲区中数据不足一行，但是也不多，就等等新数据的到来
            return true;
        }
        if (line.size() > Max_Line)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 414; // URI TOO LONG
            return false;
        }
        bool ret = ParseLine(line);
        if (ret == false)
        {
            return false;
        }
        // 行处理完到头部处理了
        _recv_statu = RECV_HTTP_HEAD;
        return true;
    }
    bool ParseHead(std::string &line)
    {
        // key: val\r\nkey: val\r\n....
        // if (line.back() == '\r')
        //     line.pop_back();
        // if (line.back() == '\n')
        //     line.pop_back();
        //注意顺序，反了bug
        if (line.back() == '\n')
            line.pop_back();
        if (line.back() == '\r')
            line.pop_back();
        size_t pos = line.find(": ");
        if (pos == std::string::npos)
        {
            _recv_statu = RECV_HTTP_ERROR;
            _resp_statu = 400;
            return false;
        }
        std::string key = line.substr(0, pos);
        std::string value = line.substr(pos + 2); // 有个空格所以+2
        _request.SetHead(key, value);
        return true;
    }
    bool RecvHead(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_HEAD)
        {
            return false;
        }
        while (1)
        {
            std::string line = buf->GetLineAndPop();
            if (line.size() == 0)
            {
                // 考虑缓冲区数据不到一行，但是一行内容过大也是错误
                if (buf->ReadAbleSize() > Max_Line)
                {
                    _recv_statu = RECV_HTTP_ERROR;
                    _resp_statu = 414; // URI TOO LONG
                    return false;
                }
                // 缓冲区中数据不足一行，但是不多，等等新数据的到来
                return true;
            }
            if (line.size() > Max_Line)
            {
                _recv_statu = RECV_HTTP_ERROR;
                _resp_statu = 414; // URI TOO LONG
                return false;
            }
            // 头部与正文中间有空行，到正文了
            if (line == "\n" || line == "\r\n")
                break;
            bool ret = ParseHead(line);
            if (ret == false)
            {
                return false;
            }
        }
        _recv_statu = RECV_HTTP_BODY;
        return true;
    }
// GetLineAndPop(): 读取一行并从缓冲区移除该行

// ReadMoveOffset(): 移动读指针，表示这些数据已被处理

// 所以当进入 Recvbody() 时，缓冲区中只剩下正文数据，头部已经被消费掉了。
    bool Recvbody(Buffer *buf)
    {
        if (_recv_statu != RECV_HTTP_BODY)
            {return false;}
        size_t content_length = _request.GetContentLength();
        if (content_length == 0)
        {
            // 正文长度为0接受结束了
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        // 实际还需要接受正文长度
        size_t real_length = content_length - _request._body.size(); //
        // 接收正文放到body中，但是也要考虑当前缓冲区中的数据，是否是全部的正文
        // 缓冲区中数据，包含了当前请求的所有正文，则取出所需的数据
        ////////////////////////一定注意这个=，刚开始假设写入686字节此时就是，CONNECION里的handleread,经过行和头部解析此时缓冲区只剩下正文了，此时缓冲区就是50，然后read_length刚开始是50，
        if (real_length <= buf->ReadAbleSize())
        {
            _request._body.append(buf->ReadPosition(), real_length);
            buf->ReadMoveOffset(real_length);
            _recv_statu = RECV_HTTP_OVER;
            return true;
        }
        _request._body.append(buf->ReadPosition(), buf->ReadAbleSize()); //  3.2 缓冲区中数据，无法满足当前正文的需要，数据不足，取出数据，然后等待新数据到来
        buf->ReadMoveOffset(buf->ReadAbleSize());
        // 若为POST请求，解析body中的表单数据
        if (_request._method == "POST") {
            _request.ParsePostBody();
        }
        return true;
    }

public:
    HttpContext() : _resp_statu(200), _recv_statu(RECV_HTTP_LINE) {}
    void ReSet()
    {
        _resp_statu = 200;
        _recv_statu = RECV_HTTP_LINE;
        _request.ReSet();
    }
    int RespStatu() { return _resp_statu; }
    HttpRecvStatu RecvStatu() { return _recv_statu; }
    HttpRequest &Request() { return _request; }
    // 接收并解析HTTP请求
    void RecvHttpRequest(Buffer *buf)
    {
        switch (_recv_statu)
        {
        case RECV_HTTP_LINE:
            RecvLine(buf);
        case RECV_HTTP_HEAD:
            RecvHead(buf);
        case RECV_HTTP_BODY:
            Recvbody(buf);
        }
        return;
    }
};

class Httpserver
{
private:
    using Handler = std::function<void(const HttpRequest &, HttpResponse *)>;
    using Handlers = std::vector<std::pair<std::regex, Handler>>; // 正则表达式对应的
    Handlers _get_route;
    Handlers _post_route;
    Handlers _put_route;
    Handlers _delete_route;
    std::string _basedir; // 静态资源根目录
    Tcpserver _server;

private:
public:
    void ErrorHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        // 1. 组织一个错误展示页面
        std::string body;
        body += "<html>";
        body += "<head>";
        body += "<meta http-equiv='Content-Type' content='text/html;charset=utf-8'>";
        body += "</head>";
        body += "<body>";
        body += "<h1>";
        body += std::to_string(rsp->_statu);
        body += " ";
        body += Util::GetStatu(rsp->_statu);
        body += "</h1>";
        body += "</body>";
        body += "</html>";
        // 2. 将页面数据，当作响应正文，放入rsp中
        rsp->SetContent(body, "text/html");
    }
    // 将HttpResponse中的要素按照http协议格式进行组织，发送
    void WriteResponse(const PtrConnection &conn, HttpRequest &req, HttpResponse &rsp)
    {
        // 1. 先完善头部字段
        if (req.Close() == true)
        {
            rsp.SetHeader("Connection", "close");
        }
        else
        {
            rsp.SetHeader("Connection", "keep-alive");
        }
        if (rsp._body.empty() == false && rsp.HashHeader("Content-Length") == false)
        {
            rsp.SetHeader("Content-Length", std::to_string(rsp._body.size()));
        }
        if (rsp._body.empty() == false && rsp.HashHeader("Content-Type") == false)
        {
            rsp.SetHeader("Content-Type", "application/octet-stream");
        }
        if (rsp._redirect_flag == true)
        {
            rsp.SetHeader("Location", rsp._redirect_url);
        }
        // 2
        std::stringstream rsp_str;
        rsp_str << req._version << " " << std::to_string(rsp._statu) << " " << Util::GetStatu(rsp._statu) << "\r\n";
        for (auto &head : rsp._headers)
        {
            rsp_str << head.first << ": " << head.second << "\r\n";
        }
        rsp_str << "\r\n";
        rsp_str << rsp._body;
        // 3. 发送数据
        conn->Send(rsp_str.str().c_str(), rsp_str.str().size());
    }
    bool IsFileHandler(HttpRequest &req)
    {
        if (_basedir.empty())
        {
            return false;
        }
        // 2. 请求方法，必须是GET / HEAD请求方法
        if (req._method != "GET" && req._method != "HEAD")
        {
            return false;
        }
        // 3. 请求的资源路径必须是一个合法路径
        if (Util::ValidPath(req._path) == false)
        {
            return false;
        }
        // 4. 请求的资源必须存在,且是一个普通文件
        //    有一种请求比较特殊 -- 目录：/, /image/， 这种情况给后边默认追加一个 index.html
        // index.html    /image/a.png
        // 不要忘了前缀的相对根目录,也就是将请求路径转换为实际存在的路径  /image/a.png  ->   ./wwwroot/image/a.png
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
        {
            req_path += "index.html";
        }
        if ((Util::Is_regularfile(req_path)) == false)
        {
            return false;
        }
        return true;
    }
    // 静态资源的请求处理 --- 将静态资源文件的数据读取出来，放到rsp的_body中, 并设置mime
    void FileHandler(const HttpRequest &req, HttpResponse *rsp)
    {
        std::string req_path = _basedir + req._path;
        if (req._path.back() == '/')
        {
            req_path += "index.html";
        }
        bool ret = Util::ReadFile(req_path, &(rsp->_body));
        if (ret == false)
        {
            return;
        }
        std::string mime = Util::Getmime(req_path);
        rsp->SetHeader("Content-Type", mime);
        return;
    }
    void DisPatcher(HttpRequest &req, HttpResponse *rsp, Handlers& handlers)
    {
        DBG_LOG("Dispatcher: 方法=%s, 路径=%s, 处理器数量=%lu", 
            req._method.c_str(), req._path.c_str(), handlers.size());
        // 在对应请求方法的路由表中，查找是否含有对应资源请求的处理函数，有则调用，没有则发挥404
        // 路由表存储的时键值对 -- 正则表达式 & 处理函数
        // 使用正则表达式，对请求的资源路径进行正则匹配，匹配成功就使用对应函数进行处理
        //   /numbers/(\d+)       /numbers/12345
        for (auto &handler : handlers)
        {
            const std::regex &re = handler.first;
            const Handler &functor = handler.second;
            bool ret = std::regex_match(req._path, req._matches, re);
            if (ret == false)
            {
                continue;
            }
            return functor(req, rsp); // 传入请求信息，和空的rsp，执行处理函数
        }
        rsp->_statu = 404;
    }
    void Route(HttpRequest &req, HttpResponse *rsp)
    {
         DBG_LOG("=== 进入Route函数 ===");
        DBG_LOG("方法: %s, 路径: %s", req._method.c_str(), req._path.c_str());
        // 1. 对请求进行分辨，是一个静态资源请求，还是一个功能性请求
        //    静态资源请求，则进行静态资源的处理
        //    功能性请求，则需要通过几个请求路由表来确定是否有处理函数
        //    既不是静态资源请求，也没有设置对应的功能性请求处理函数，就返回405
        if (IsFileHandler(req) == true)
        {
            FileHandler(req, rsp);
            return;
        }
        if (req._method == "GET" || req._method == "HEAD")
        {
            return DisPatcher(req, rsp, _get_route);
        }
        else if (req._method == "POST")
        {
            return DisPatcher(req, rsp, _post_route);
        }
        else if (req._method == "PUT")
        {
            return DisPatcher(req, rsp, _put_route);
        }
        else if (req._method == "DELETE")
        {
            return DisPatcher(req, rsp, _delete_route);
        }
    }
    void Onconnected(const PtrConnection conn) // 连接回调设置上下文
    {
        conn->SetContext(HttpContext());
        DBG_LOG("NEW CONNECTION %p", conn.get());
    }
    void OnMessage(const PtrConnection conn, Buffer *buffer)
    {
        DBG_LOG("=== 收到新消息 ===");
        DBG_LOG("缓冲区大小: %lu", buffer->ReadAbleSize());
        while(buffer->ReadAbleSize() > 0) 
        {
        // 1. 获取上下文
        HttpContext *context = conn->Getcontext()->get<HttpContext>();
        DBG_LOG("当前解析状态: %d", context->RecvStatu());
        // 2. 通过上下文对缓冲区数据进行解析，得到HttpRequest对象
        //   1. 如果缓冲区的数据解析出错，就直接回复出错响应
        //   2. 如果解析正常，且请求已经获取完毕，才开始去进行处理
        context->RecvHttpRequest(buffer);
        HttpRequest &req = context->Request();
        HttpResponse rsp(context->RespStatu());
         DBG_LOG("解析后状态: %d, 响应状态: %d", 
                context->RecvStatu(), context->RespStatu());
        DBG_LOG("方法: %s, 路径: %s, 版本: %s", 
                req._method.c_str(), req._path.c_str(), req._version.c_str());
        DBG_LOG("正文长度: %lu, 实际正文: %lu", 
                req.GetContentLength(), req._body.size());
        if (rsp._statu >= 400) // 出错
        {
            DBG_LOG("!!! 解析出错，状态码: %d !!!", context->RespStatu());
            ErrorHandler(req, &rsp);       // 填充错误页面
            WriteResponse(conn, req, rsp); // 发送响应到客户端
            /////一定重置这个context
            context->ReSet();
            buffer->ReadMoveOffset(buffer->ReadAbleSize()); // 出错了就把缓冲区数据清空
            conn->Shutdown();
            return;
        }
        if (context->RecvStatu() != RECV_HTTP_OVER)
        {
             DBG_LOG("请求解析未完成，等待更多数据");
            // 当前请求还没有接收完整,则退出，等新数据到来再重新继续处理
            return;
        }
        DBG_LOG("*** 请求解析完成，开始路由处理 ***");
        // 3请求路由业务处理
        Route(req, &rsp);
        // 4对response组织发送
        WriteResponse(conn, req, rsp);

        // 5重置上下文
        context->ReSet();
        // 6判断长短连接，短链接直接关闭
        if (rsp.Close() == true)
            conn->Shutdown();
        }
        return;
    }
public:
    Httpserver(int port, int timeout = DEFALT_TIMEOUT) : _server(port)
    {
        _server.EnableInactiveRelease(timeout);
        _server.SetConnectedCallback(std::bind(&Httpserver::Onconnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&Httpserver::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }
    void SetBaseDir(const std::string &path)
    {
        assert(Util::IsDirectory(path) == true);
        _basedir = path;
    }
    /*设置/添加，请求（请求的正则表达）与处理函数的映射关系*/
    void Get(const std::string &res, const Handler &handler)
    {
        _get_route.push_back(std::make_pair(std::regex(res), handler));
    }
    void Post(const std::string &res, const Handler &handler)
    {
        _post_route.push_back(std::make_pair(std::regex(res), handler));
    }
    void Put(const std::string &res, const Handler &handler)
    {
        _put_route.push_back(std::make_pair(std::regex(res), handler));
    }
    void Delete(const std::string &res, const Handler &handler)
    {
        _delete_route.push_back(std::make_pair(std::regex(res), handler));
    }
    void SetThreadCount(int count)
    {
        _server.SetThreadCount(count);
    }
    void Listen()
    {
        _server.Start();
    }
};
